package fr.utbm.lo54.domain;

import java.util.Date;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findSessionsByStartEqualsAndLocationAndCourse" })
public class Session {

	@Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MS")
    private Date start;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MS")
    private Date end;

    @ManyToOne
    private Course course;

    @ManyToOne
    private Location location;
    
    public static TypedQuery<Session> findSessionsByStartEqualsAndLocationAndCourse(Date start, Location location, Course course) {
        EntityManager em = Session.entityManager();
        Date datefin = null;
        String query = "SELECT o FROM Session AS o WHERE 1=1 ";
        System.out.println(start);
        if (start != null) {
        	datefin = new Date(start.getTime());
        	datefin.setHours(23);
        	datefin.setMinutes(59);
        	datefin.setSeconds(59);
        	query += "AND o.start > :start ";
        	query += "AND o.start < :datefin ";
        }
        if (location != null)
        	query += "AND o.location = :location ";
        if (course != null)
        	query += "AND o.course = :course ";
        TypedQuery<Session> q = em.createQuery(query, Session.class);
        if (start != null) {
        	q.setParameter("start", start);
        	q.setParameter("datefin",datefin);
        }
        if (location != null)
        	 q.setParameter("location", location);
        if (course != null)
        	 q.setParameter("course", course);
        return q;
    }

	public Course getCourse() {
		return course;
	}

	public void setCourse(Course course) {
		this.course = course;
	}
	public String toString() {
		return course.toString();
	}

}
